///\todo upgrade

//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#ifndef __BUOLA_IO_CSOCKETACCEPTOR_H__
#define __BUOLA_IO_CSOCKETACCEPTOR_H__

#include <buola/io/csocket.h>
#include <buola/io/cfdpoller.h>
#include <buola/io/cfdlistener.h>
#include <sys/socket.h>
#include <unistd.h>

namespace buola { namespace io {

///\addtogroup network
///@{

///////////////////////////////////////////////////////////////////////

/// stream to do IO to/from sockets

/// it is also used to create connection sockets
///////////////////////////////////////////////////////////////////////

class CSocketAcceptor : public CFDListener
{
public:
//! \name constructor and destructor
//@{
    CSocketAcceptor(NFromFD,int pFD,ESocketType pType)
        :   mFD(pFD)
        ,   mSocketType(pType)
    {
    }

    CSocketAcceptor(const CSocketAcceptor&)=delete;
    CSocketAcceptor &operator=(const CSocketAcceptor&)=delete;
    
    virtual ~CSocketAcceptor()
    {
        Close();
    }
//@}

//! \name open and close the connection
//@{
    void Close()
    {
        if(mFD==-1) return;

        ::close(mFD);
        
        mFD=-1;
        //TODO:do something about linger and about nonblocking... see asio
    }

    void Listen(int pBackLog=SOMAXCONN)
    {
        if(mFD==-1) throw XInvalid("trying to listen in a non-open socket");
        ::listen(mFD,pBackLog);
    }
//@}

//! \name accept incoming connections
//@{
    io::PSocket Accept()
    {
        if(mFD==-1) throw XInvalid("trying to accept in a non-open socket");
//      int lFD=::accept4(mFD,nullptr,nullptr,0); //valgrind doesn't like it
        int lFD=::accept(mFD,nullptr,nullptr);

        //set linger back!
        struct linger lLing;
        lLing.l_onoff=1;
        lLing.l_linger=1;
        setsockopt(lFD,SOL_SOCKET,SO_LINGER,&lLing,sizeof(lLing));

        return new CSocket(nFromFD,lFD,mSocketType);
    }

    template<typename tHandler>
    void AcceptAsync(const tHandler &pHandler,CFDPoller &pPoller=get_main_fd_poller())
    {
        if(mFD==-1) throw XInvalid("trying to accept in a non-open socket");
        mHandler=pHandler;
        pPoller.AddFDListener(this,mFD,io::ENotify::READ);
    }
//@}

private:
//! \name event handling
//@{
    void OnFDListener(int pFD,io::ENotify pWhat,void*)
    {
        msg_info() << "onfdlistener " << pFD << "\n";
        mHandler(Accept());
    }
//@}

private:
    int mFD;
    ESocketType mSocketType;

    std::function<void(PSocket)> mHandler;
};

template<typename tEndPoint>
std::unique_ptr<CSocketAcceptor> listen_at(const tEndPoint &pEndPoint,ESocketType pType=ESocketType::NONE,int pBackLog=64)
{
    std::unique_ptr<CSocketAcceptor> lResult=pEndPoint.GetBoundSocket(pType);
    lResult->Listen(pBackLog);
    return lResult;
}

///@}

/*namespace io*/ } /*namespace buola*/ }

#endif
